package com.gitee.kamismile.stoneComEx.util;

//import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 文件上传工具类
 *
 * @author songdawei
 *
 */
public class FileUploadUtil {


//	public static boolean doUpload(HttpServletRequest request, String fileName) {
//		try {
//			InputStream in = request.getInputStream();
//			return doUpload(in,fileName);
//		} catch (IOException e) {
//			e.printStackTrace();
//			return false;
//		}finally{
//
//		}
//	}



	public static boolean doUpload(InputStream in, String fileName) {
		BufferedOutputStream bos = null;
		try {
			File f1 = new File(fileName);
			if(!f1.exists()){
				File pa = f1.getParentFile();
				while(!pa.exists())
					pa.mkdirs();
				f1.createNewFile();
			}
			FileOutputStream fos = new FileOutputStream(fileName);
			bos = new BufferedOutputStream(fos);
			getFileContent(bos,in);
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			try {
				if(bos!=null)
					bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}



	public static File[] doMutilUpload(InputStream ins, String dirPath,
			String filterFile, String resFile){
		return (File[]) doMutilUploadAll(ins, dirPath, filterFile, resFile)[1];

	}

	/**
	 *
	 * 批量上传
	 *
	 * @param ins
	 *            http二进制流
	 * @param dirPath
	 *            文件存放路径
	 * @param filterFile
	 *            过滤文件类型(后缀名)(jpg,gif,bmp,zip,)最后一定要有','符号，不限制就可以不传参数
	 * @param resFile
	 *            保存后的文件类型(后缀名)（不填写就是默认的上传文件类型）
	 * @return
	 */
	public static Object[] doMutilUploadAll(InputStream ins, String dirPath,
			String filterFile, String resFile) {
		List<File> files = new ArrayList<File>();
		HashMap<String,String> parameters = new HashMap<String,String>();
		try {
			File dir = new File(dirPath);
			if(!dir.exists())
				dir.mkdirs();
			BufferedInputStream bis = new BufferedInputStream(ins);
			byte[] firstLine = readStreamLine(bis);
			while (bis.read() != -1) {
				String content_disposition = new String(readStreamLine(bis),"ASCII");
				int index = content_disposition.lastIndexOf(".");
				String fileType = null;// 文件后缀名称
				if (content_disposition.indexOf("filename=\"") != -1) {
					readStreamLine(bis);
					readStreamLine(bis);
					boolean filter = true;
					if (index > 0) {
						fileType = content_disposition.substring(index + 1,content_disposition.length() - 3).toLowerCase();
						if (filterFile != null&& filterFile.toLowerCase().indexOf(fileType.toLowerCase() + ",") == -1) {
							filter = false;
						}
					}
					byte[] lineData = readStreamLine(bis);
					if (lineData.length > 2 && lineData[1] != '\n'&& fileType != null && filter == true) {
						FileOutputStream fos = null;
						long now = System.currentTimeMillis()+files.size();
						String filePath = dirPath + File.separatorChar+ now + "."+resFile;
						if (resFile.toLowerCase().equals("jpg")) {
							filePath = dirPath + File.separatorChar+ now+"."+fileType;
						}
						fos = new FileOutputStream(filePath);
						fos.write(lineData);
						while ((lineData = readStreamLine(bis)) != null) {
							if (!isByteArraystartWith(lineData, firstLine)) {
								fos.write(lineData);
							} else {
								break;
							}
						}
						fos.flush();
						fos.close();
						files.add(new File(filePath));
					} else {
						while (isByteArraystartWith(readStreamLine(bis),firstLine))
							break;
					}
				} else {
					readStreamLine(bis);
					// readStreamLine(bis);
					int _begin = content_disposition.indexOf("form-data; name=\"");
					int _end   = content_disposition.lastIndexOf("\"");
					if(_begin!=-1 ){
						byte src[] = readStreamLine(bis);
						byte[] paramArrays = new byte[src.length-2];
						System.arraycopy(src, 0, paramArrays, 0, paramArrays.length);
						String param = new String(paramArrays,"UTF-8");
						parameters.put(content_disposition.substring(_begin+17,_end),param);
					}
					byte[] lineData = null;
					while ((lineData = readStreamLine(bis)) != null) {
						if (isByteArraystartWith(lineData, firstLine)) {
							break;
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return new Object[]{parameters,files.toArray(new File[files.size()])};
	}


	public static boolean uploadTwoImage(String fileSave1, String fileSave2, InputStream ins, String sign) {
		boolean ret = true;
		FileOutputStream fos1 = null;
		FileOutputStream fos2 = null;
		try {
			BufferedInputStream bis = new BufferedInputStream(ins);
			File file1 = new File(fileSave1);
			File file2 = new File(fileSave2);
			if (!file1.getParentFile().exists()) {
				file1.getParentFile().mkdirs();
			}
			if (!file1.exists()) {
				file1.createNewFile();
			}
			if (!file2.exists()) {
				file2.createNewFile();
			}
			fos1 = new FileOutputStream(file1);
			fos2 = new FileOutputStream(file2);
			byte[] date = null;
			boolean division = true;
			while ((date = readStreamLine(bis)) != null) {
				if((new String(date, "ASCII")).indexOf(sign) >= 0){
					division = false;
					continue;
				}
				if (division)
					fos1.write(date);
				else
					fos2.write(date);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				if (fos1 != null)
					fos1.close();
				if (fos2 != null)
					fos2.close();
				if (ins != null)
					ins.close();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return ret;
	}



	private static String getFileContent(BufferedOutputStream bos,InputStream is) throws IOException {
		int index;
		boolean isEnd = false;
		byte[] lineSeparatorByte;
		byte[] lineData;
		String content_disposition;
		//ByteArrayOutputStream bos = new ByteArrayOutputStream();
		BufferedInputStream bis = new BufferedInputStream(is);

		lineSeparatorByte = readStreamLine(bis);
		while (!isEnd) {

			lineData = readStreamLine(bis);
			if (lineData == null) {
				break;
			}
			content_disposition = new String(lineData, "ASCII");
			index = content_disposition.indexOf("filename=\"") - 4;
			if (index >= 0 && index < content_disposition.length()) {
				readStreamLineAsString(bis); // skip a line
				readStreamLineAsString(bis); // skip a line


				byte bt[] = null;
				lineData = readStreamLine(bis);
				bt = lineData;
				while ((lineData = readStreamLine(bis)) != null) {
					if (isByteArraystartWith(lineData, lineSeparatorByte)) { // end
						isEnd = true;
						break;
					} else {
						bos.write(bt);
						bt = lineData;
					}

				}
				if(bt!=null && bt.length>=3){
					bos.write(bt,0,bt.length-2);
				}
				bos.flush();
			} else {
				lineData = readStreamLine(bis);
				if (lineData == null)
					return null;
				while (!isByteArraystartWith(lineData, lineSeparatorByte)) {
					lineData = readStreamLine(bis);
					if (lineData == null)
						return null;
				}
			}
		}
		return "1";
	}

	private static byte[] readStreamLine(BufferedInputStream in)
	throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		int b = in.read();
		if (b == -1)
			return null;
		while (b != -1) {
			bos.write(b);
			if (b == '\n')
				break;
			b = in.read();
		}
		return bos.toByteArray();
	}

	private static String readStreamLineAsString(BufferedInputStream in)
	throws IOException {
		if(in.available() > 0)
			return new String(readStreamLine(in), "ASCII");
		else
			return null;
	}

	private static boolean isByteArraystartWith(byte[] arr, byte[] pat) {
		int i;
		if (arr == null || pat == null)
			return false;
		if (arr.length < pat.length)
			return false;
		for (i = 0; i < pat.length; i++) {
			if (arr[i] != pat[i])
				return false;
		}
		return true;
	}
}
